package org.example.day8;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class Producer {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        String serverList = "192.168.64.2:9092";
        String topic = "topic_test";
        Properties prop = new Properties();

        // 2.给 Kafka 配置对象添加配置信息
        prop.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, serverList);
        // 2.2 配置 key.serializer 和 value.serializer
        prop.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        prop.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        // 3.创建 Kafka 生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(prop);
        // 4.调用 send 方法，发送消息

        // 不指定key和分区
//        for (int i = 0; i < 5; i++) {
//            ProducerRecord<String, String> record = new ProducerRecord<>(topic, "demo" + i);
//            kafkaProducer.send(record, new Callback() {
//                @Override
//                public void onCompletion(RecordMetadata metadata, Exception exception) {
//                    System.out.println("消息所在分区："+metadata.partition());
//                }
//            });
//        }
        // 指定相同的key
//        for (int i = 0; i < 5; i++) {
//            ProducerRecord<String, String> record = new ProducerRecord<>(topic, "相同的key","demo" + i);
//            kafkaProducer.send(record, new Callback() {
//                @Override
//                public void onCompletion(RecordMetadata metadata, Exception exception) {
//                    System.out.println("消息所在分区："+metadata.partition());
//                }
//            });
//        }
        // 指定不同的key
//        for (int i = 0; i < 5; i++) {
//            ProducerRecord<String, String> record = new ProducerRecord<>(topic, "不同的key"+i,"demo" + i);
//            kafkaProducer.send(record, new Callback() {
//                @Override
//                public void onCompletion(RecordMetadata metadata, Exception exception) {
//                    System.out.println("消息所在分区："+metadata.partition());
//                }
//            });
//        }
        // 指定partition
        for (int i = 0; i < 5; i++) {
            ProducerRecord<String, String> record = new ProducerRecord<>(topic,2, "不同的key","demo" + i);
            kafkaProducer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata metadata, Exception exception) {
                    System.out.println("消息所在分区："+metadata.partition());
                }
            });
        }
        Thread.sleep(10000);
    }
}
